<template>
	<view class="m-progress-view" @touchstart="touchStart" @touchmove="touchMove">
		<view class="m-progress">
			<view :class="theme" class="m-progress-bg" :style="[{width: this.left + 17 + 'px'}]"></view>
			<view class="m-progress-pointer" :style="[{left: this.left + 'px'}]"></view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			theme: {
				type: String, // color-ui 的颜色class
				default: 'bg-blue'
			},
			value: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				left: 0,
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			async init() {
				this.progress = await this.nodeInfo('.m-progress');
				this.pointer = await this.nodeInfo('.m-progress-pointer');
				this.width = this.progress.width - this.pointer.width;
				this.left = this.width * ((this.value || 0) / 100);
			},
			nodeInfo(name) {
				return new Promise(resolve => {
					const query = uni.createSelectorQuery().in(this);
					query.select(name).boundingClientRect(res => {
						resolve(res)
					}).exec();
				})
			},
			praseEventPos(e) {
				const {
					touches: [{
						clientX,
						clientY
					}]
				} = e;
				return [clientX, clientY]
			},
			setSliderPointerValue(clientX, clientY) {
				if (!this.progress) return;
				let x = clientX - this.progress.left - (this.pointer.width / 2);
				if (x <= 0) {
					x = 0;
				} else if (x >= this.width) {
					x = this.width;
				}
				this.lightness = parseInt(x / this.width * 100)
				this.left = x;
			},
			touchStart(e) {
				this.setSliderPointerValue(...this.praseEventPos(e))
				this.change();
			},
			touchMove(e) {
				this.setSliderPointerValue(...this.praseEventPos(e));
				this.change();
			},
			change() {
				this.$emit('change', this.lightness)
				this.$emit('input', this.lightness)
			}
		}
	}
</script>

<style>
	.m-progress-view {
		padding: 8px 0;
	}

	.m-progress {
		height: 9px;
		border-radius: 10px;
		position: relative;
		background: #e4e4e4;
	}

	.m-progress-pointer {
		display: inline-block;
		position: absolute;
		border: 4px solid #fff;
		border-radius: 50%;
		background: transparent;
		box-sizing: content-box;
		width: 9px;
		height: 9px;
		top: -4px;
		left: 0;
		box-shadow: 0px 0px 1px 2px #cacaca82;
		z-index: 99;
	}

	.m-progress-bg {
		position: absolute;
		width: 0;
		left: 0;
		top: 0;
		height: 100%;
		border-radius: 10px;
		z-index: 9;
	}
</style>
